import base64
import json
import os
from typing import Any

from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, StreamingResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel

from config.yaml_settings import get_llm_api_config, get_server_config
from core.workflow_manager import workflow_manager
from workflow.ReportAnalysisWorkflowV2 import ReportAnalysisWorkflowV2

# 创建FastAPI应用
app = FastAPI(title="智能报表分析API", description="基于AutoGen和预定义SQL工具的智能报表分析系统")

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# 挂载静态文件
if os.path.exists("static"):
    app.mount("/static", StaticFiles(directory="static"), name="static")

# 配置参数
api_config = get_llm_api_config()
server_config = get_server_config()


# 请求模型
class AnalysisRequest(BaseModel):
    query: str
    api_key: str = api_config.api_key
    base_url: str = api_config.base_url


# 响应模型
class AnalysisResponse(BaseModel):
    status: str
    user_query: str
    sql_query: str = None
    data: Any = None
    html_report: str = None
    chart_config: str = None  # 保持兼容性
    error: str = None
    html_encoded: bool = False  # 标记HTML是否已经Base64编码


@app.get("/")
async def root():
    """根路径 - 返回前端页面"""
    if os.path.exists("static/index.html"):
        return FileResponse("static/index.html")
    return {"message": "智能报表分析API服务正在运行"}


@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "intelligent-report-analysis-api"}


@app.post("/analyze", response_model=AnalysisResponse)
async def analyze_report_data(request: AnalysisRequest):
    """报表数据分析接口 - 非流式版本"""
    try:
        # 获取工作流实例
        workflow = await get_workflow(request.api_key, request.base_url)

        # 执行分析
        result = await workflow.analyze_report_data(request.query)
        
        # 直接返回HTML报告，不进行base64编码
        if result.get("html_report"):
            result["html_encoded"] = False

        return AnalysisResponse(**result)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"分析失败: {str(e)}")


@app.post("/analyze/stream")
async def analyze_report_data_stream(request: AnalysisRequest):
    """报表数据分析接口 - 流式版本"""

    async def generate_stream():
        try:
            # 使用重构后的工作流管理器执行流式分析
            async for step_result in workflow_manager.execute_report_analysis_stream(
                request.query, 
                request.api_key, 
                request.base_url
            ):
                # 处理可能包含不可序列化对象的数据
                serializable_result = {}
                for key, value in step_result.items():
                    if key == 'data' and value is not None:
                        # 如果data是复杂对象，转换为字符串并清理特殊字符
                        if isinstance(value, (dict, list)):
                            data_str = str(value)
                        else:
                            data_str = str(value)

                        # 清理可能导致JSON解析错误的字符
                        data_str = data_str.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace('\r',
                                                                                                                   '\\r')
                        # 截断过长的数据
                        if len(data_str) > 10000:
                            data_str = data_str[:10000] + "...[数据已截断]"
                        serializable_result[key] = data_str

                    elif key == 'field_info' and value is not None:
                        # 字段信息可能很长，截断显示
                        field_str = str(value)
                        field_str = field_str.replace('\\', '\\\\').replace('"', '\\"').replace('\n', '\\n').replace(
                            '\r', '\\r')
                        serializable_result[key] = field_str[:1000] + "..." if len(field_str) > 1000 else field_str

                    elif key == 'html_report' and value is not None:
                        # 直接返回HTML报告，不进行base64编码
                        serializable_result[key] = str(value)
                        serializable_result['html_encoded'] = False

                    else:
                        # 其他字段直接转换
                        serializable_result[key] = str(value) if value is not None else None

                try:
                    # 将每个步骤的结果转换为JSON并发送
                    json_str = json.dumps(serializable_result, ensure_ascii=False)
                    yield f"data: {json_str}\n\n"
                except Exception as json_error:
                    # 如果JSON序列化失败，发送错误信息
                    error_result = {
                        "step": step_result.get("step", "unknown"),
                        "status": "error",
                        "error": f"JSON序列化失败: {str(json_error)}",
                        "message": "数据序列化失败"
                    }
                    yield f"data: {json.dumps(error_result, ensure_ascii=False)}\n\n"

        except Exception as e:
            # 发送错误信息
            error_result = {
                "step": "error",
                "status": "error",
                "error": str(e),
                "message": f"流式分析失败: {str(e)}"
            }
            yield f"data: {json.dumps(error_result, ensure_ascii=False)}\n\n"

    return StreamingResponse(
        generate_stream(),
        media_type="text/plain",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Type": "text/event-stream"
        }
    )


@app.get("/status")
async def get_workflow_status():
    """获取工作流状态"""
    try:
        workflow = await workflow_manager.get_report_workflow()
        status = await workflow.get_workflow_status()
        return status
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取状态失败: {str(e)}")


@app.get("/tools")
async def get_available_tools():
    """获取可用的SQL工具列表"""
    try:
        workflow = await workflow_manager.get_report_workflow()
        status = await workflow.get_workflow_status()
        return {
            "available_tools": status.get("available_tools", []),
            "description": "预定义的SQL查询工具列表"
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取工具列表失败: {str(e)}")


@app.post("/test")
async def test_analysis():
    """测试分析功能"""
    test_queries = [
        "帮我分析2024年1月到6月的财务情况",
        "分析最近30天的用户活跃度",
        "统计最近3个月的销售数据"
    ]

    results = []
    try:
        for query in test_queries:
            result = await workflow_manager.execute_report_analysis(query)
            results.append({
                "query": query,
                "result": result
            })

        return {
            "message": "测试完成",
            "results": results
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"测试失败: {str(e)}")


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host=server_config.host, port=server_config.port)